﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories;

namespace EcoSystem
{
    public class BucketAppService : CrudAppService<
        Bucket,
        BucketDto,
        string,
        GetBucketInput,
        CreateOrUpdateBucketDto,
        CreateOrUpdateBucketDto>, IBucketAppService
    {
        public BucketAppService(IRepository<Bucket, string> repository) : base(repository)
        {

        }

        public override async Task<BucketDto> CreateAsync(CreateOrUpdateBucketDto input)
        {
            var entity = MapToEntity(input);
            EntityHelper.TrySetId(entity, () => input.Id);
            await this.Repository.InsertAsync(entity, true);
            return MapToGetListOutputDto(entity);
        }

        public override async Task<PagedResultDto<BucketDto>> GetListAsync(GetBucketInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
            .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.Id.Contains(input.Name) || x.Description.Contains(input.Name))
            .WhereIf(input.Status.HasValue, x => x.Status == input.Status);
            var total = await query.CountAsync();
            var items = await query.OrderBy(x => x.Id).PageBy(input).ToListAsync();
            return new PagedResultDto<BucketDto>()
            {
                Items = await MapToGetListOutputDtosAsync(items),
                TotalCount = total
            };
        }

        public async Task<List<BucketDto>> GetAllListAsync(GetBucketInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
                      .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.Id.Contains(input.Name) || x.Description.Contains(input.Name))
                      .WhereIf(input.Status.HasValue, x => x.Status == input.Status);
            var items = await query.OrderBy(x => x.Id).ToListAsync();
            return await MapToGetListOutputDtosAsync(items);
        }
    }
}
